////
////  ChatViewController.swift
////  myhub
////
////  Created by x on 2024/3/6.
////
//
//import UIKit
//import MessageKit
//import InputBarAccessoryView
//import RxSwift
//import DesignKit
//
//
//open class ChatViewController: MessagesViewController {
//    var messages: [MessageType] = [] {
//        didSet {
//            self.messagesCollectionView.reloadData()
//        }
//    }
//
//    let sendPressed = PublishSubject<String>()
//    let senderSelected = PublishSubject<SenderType>()
//    let mentionSelected = PublishSubject<String>()
//    let hashtagSelected = PublishSubject<String>()
//    let urlSelected = PublishSubject<URL>()
//
//    let currentUser = User.currentUser()
//
//    /// The object that manages autocomplete, from InputBarAccessoryView
//    lazy var autocompleteManager: AutocompleteManager = {
//        [unowned self] in
//        let manager = AutocompleteManager(for: self.messageInputBar.inputTextView)
//        manager.delegate = self
//        manager.dataSource = self
//        return manager
//    }()
//
//    open override func viewDidLoad() {
//        super.viewDidLoad()
//        makeUI()
//        bindViewModel()
//    }
//
//    open func makeUI() {
//        configureMessageCollectionView()
//        configureMessageInputBar()
//        configureAutocomplete()
//    }
//
//    open func bindViewModel() {
//
//    }
//    open func configureAutocomplete() {
//        // Configure AutocompleteManager
//        autocompleteManager.register(prefix: "@", with: [
//            .font: UIFont.preferredFont(forTextStyle: .body),
//            .foregroundColor: UIColor.DesignKit.secondary(),
//            .backgroundColor: UIColor.DesignKit.secondary().withAlphaComponent(0.1)
//        ])
//
//        autocompleteManager.register(prefix: "#")
//        autocompleteManager.maxSpaceCountDuringCompletion = 1 // Allow for autocompletes with a space
//        // Set plugins
//        messageInputBar.inputPlugins = [autocompleteManager]
//
//        autocompleteManager.defaultTextAttributes = [
//            .font: UIFont.preferredFont(forTextStyle: .callout),
//            .foregroundColor: UIColor.DesignKit.text()
//        ]
//
//        autocompleteManager.tableView.theme.backgroundColor = themeService.attribute { $0.primaryDark }
//    }
//
//    open func configureMessageCollectionView() {
//        messagesCollectionView.messagesDataSource = self
//        messagesCollectionView.messagesDisplayDelegate = self
//        messagesCollectionView.messagesLayoutDelegate = self
//        messagesCollectionView.messageCellDelegate = self
//
//        scrollsToLastItemOnKeyboardBeginsEditing = true
//        maintainPositionOnKeyboardFrameChanged = true
//
//        view.theme.backgroundColor = themeService.attribute { $0.primaryDark }
//        messagesCollectionView.theme.backgroundColor = themeService.attribute { $0.primaryDark }
//    }
//
//    open func configureMessageInputBar() {
//        messageInputBar.delegate = self
//        messageInputBar.inputTextView.keyboardType = .twitter
//        messageInputBar.inputTextView.cornerRadius = Dimensions.cornerRadius
//
//        messageInputBar.backgroundView.theme.backgroundColor = themeService.attribute { $0.primary }
//        messageInputBar.inputTextView.theme.backgroundColor = themeService.attribute { $0.primaryDark }
//        messageInputBar.theme.tintColor = themeService.attribute { $0.secondary }
//        messageInputBar.sendButton.theme.titleColor(from: themeService.attribute { $0.secondary }, for: .normal)
//        messageInputBar.sendButton.theme.titleColor(from: themeService.attribute { $0.secondaryDark }, for: .highlighted)
//        messageInputBar.separatorLine.theme.backgroundColor = themeService.attribute { $0.separator }
//        messageInputBar.inputTextView.theme.keyboardAppearance = themeService.attribute { $0.keyboardAppearance }
//    }
//
//    // MARK: - Helpers
//
//    public func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
//        guard indexPath.section - 1 >= 0 else { return false }
//        return (messages[indexPath.section]).sender as? User == (messages[indexPath.section - 1].sender) as? User
//    }
//
//    public func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
//        guard indexPath.section + 1 < messages.count else { return false }
//        return (messages[indexPath.section].sender as? User) == (messages[indexPath.section + 1].sender as? User)
//    }
//}
//
//extension ChatViewController: MessagesDataSource {
//    public func currentSender() -> SenderType {
//        return currentUser ?? User()
//    }
//
//    public func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
//        return messages.count
//    }
//
//    public func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
//        return messages[indexPath.section]
//    }
//
//    public func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
//        let name = message.sender.displayName
//        return NSAttributedString(string: name, attributes: [
//            NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1).bold,
//            NSAttributedString.Key.foregroundColor: UIColor.secondary()
//        ])
//    }
//
//    public func cellBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
//        let dateString = message.sentDate.toRelative(since: nil)
//        return NSAttributedString(string: dateString, attributes: [
//            NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2),
//            NSAttributedString.Key.foregroundColor: UIColor.DesignKit.text()
//        ])
//    }
//}
//
//extension ChatViewController: MessageCellDelegate {
//    public func didTapAvatar(in cell: MessageCollectionViewCell) {
//        guard let indexPath = messagesCollectionView.indexPath(for: cell),
//            let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView)
//        else {
//            return
//        }
//        senderSelected.onNext(message.sender)
//    }
//    public func didTapMessageBottomLabel(in cell: MessageCollectionViewCell) {
//        guard let indexPath = messagesCollectionView.indexPath(for: cell),
//            let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView) else {
//                return
//        }
//        senderSelected.onNext(message.sender)
//    }
//}
//
//extension ChatViewController: MessageLabelDelegate {
//    public func didSelectURL(_ url: URL) {
//        urlSelected.onNext(url)
//    }
//    public func didSelectMention(_ mention: String) {
//        mentionSelected.onNext(mention)
//    }
//    public func didSelectHashtag(_ hashtag: String) {
//        hashtagSelected.onNext(hashtag)
//    }
//}
//
//extension ChatViewController: InputBarAccessoryViewDelegate {
//
//    public func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
//        sendPressed.onNext(text)
//    }
//}
//
//extension ChatViewController: MessagesDisplayDelegate {
//
//    public func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
//        return isFromCurrentSender(message: message) ? UIColor.DesignKit.text() : UIColor.text()
//    }
//
//    public func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any] {
//        return [.foregroundColor: UIColor.DesignKit.secondary()]
//    }
//
//    public func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] {
//        return [.url, .address, .phoneNumber, .date, .transitInformation, .mention, .hashtag]
//    }
//
//    public func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
//        return isFromCurrentSender(message: message) ? UIColor.DesignKit.primary().darken(by: 0.15) : UIColor.DesignKit.primary()
//    }
//
//    public func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle {
//        let tail: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft
//        return .bubbleTail(tail, .curved)
//    }
//
//    public func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
//        if let user = message.sender as? User {
//            avatarView.isHidden = isNextMessageSameSender(at: indexPath)
//            avatarView.kf.setImage(with: user.avatarUrl?.url)
//            avatarView.borderColor = UIColor.DesignKit.secondary()
//            avatarView.borderWidth = Dimensions.borderWidth
//        }
//    }
//}
//
//extension ChatViewController: MessagesLayoutDelegate {
//    public func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
//        return 10
//    }
//
//    public func cellBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
//        return 16
//    }
//
//    public func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
//        return 0
//    }
//    public func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
//        return 22
//    }
//}
//
//extension ChatViewController: AutocompleteManagerDataSource {
//    public func autocompleteManager(_ manager: AutocompleteManager, autocompleteSourceFor prefix: String) -> [AutocompleteCompletion] {
//        switch prefix {
//        case "@":
//            return messages.map { $0.sender as? User}.withoutDuplicates().map { AutocompleteCompletion(text: $0?.displayName ?? "", context: ["avatar": $0?.avatarUrl ?? ""])}
//        default:
//            return []
//        }
//    }
//
//    public func autocompleteManager(_ manager: AutocompleteManager, tableView: UITableView, cellForRowAt indexPath: IndexPath, for session: AutocompleteSession) -> UITableViewCell {
//        guard let cell = tableView.dequeueReusableCell(withIdentifier: AutocompleteCell.reuseIdentifier, for: indexPath) as? AutocompleteCell else {
//            fatalError("Oops, some unknown error occurred")
//        }
//        let image = session.completion?.context?["avatar"] as? String
//        cell.imageView?.kf.setImage(with: image?.url)
//        cell.imageViewEdgeInsets = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
//        cell.imageView?.cornerRadius = 20
//        cell.imageView?.borderColor = UIColor.DesignKit.secondary()
//        cell.imageView?.borderWidth = Dimensions.borderWidth
//        cell.imageView?.clipsToBounds = true
//        let attributedText = manager.attributedText(matching: session, fontSize: 15)
//        attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.DesignKit.text(), range: NSRange(location: 0, length: attributedText.length))
//        cell.textLabel?.attributedText = attributedText
//        cell.backgroundColor = UIColor.DesignKit.primary()
//        cell.separatorLine.backgroundColor = UIColor.DesignKit.separator()
//        return cell
//    }
//}
//
//extension ChatViewController: AutocompleteManagerDelegate {
//    public func autocompleteManager(_ manager: AutocompleteManager, shouldBecomeVisible: Bool) {
//        setAutocompleteManager(active: shouldBecomeVisible)
//    }
//
//    // MARK: - AutocompleteManagerDelegate Helper
//    public func setAutocompleteManager(active: Bool) {
//        let topStackView = messageInputBar.topStackView
//        if active && !topStackView.arrangedSubviews.contains(autocompleteManager.tableView) {
//            topStackView.insertArrangedSubview(autocompleteManager.tableView, at: topStackView.arrangedSubviews.count)
//            topStackView.layoutIfNeeded()
//        } else if !active && topStackView.arrangedSubviews.contains(autocompleteManager.tableView) {
//            topStackView.removeArrangedSubview(autocompleteManager.tableView)
//            topStackView.layoutIfNeeded()
//        }
//        messageInputBar.invalidateIntrinsicContentSize()
//    }
//}
